import { forEach } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { getEnergyHistory, getList, getKxxbgLists, getReportTree, removeReport } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
export const useFormData = params => {
  let formdata = new FormData(); //new出来的对象
  Object.keys(params).forEach(key => {
    formdata.append(key, params[key]);
  });
  return formdata;
};

export const useCFTypeLists = () => {
  const monthLists = Array.from({ length: 12 }, (_, idx) => (idx < 9 ? `0${idx + 1}` : `${idx + 1}`));
  const waterYearlists = ref([]);
  const eleYearlists = ref([]);
  const gasYearlists = ref([]);
  const warmYearlists = ref([]);
  const waterTableData = ref([]);
  const eleTableData = ref([]);
  const gasTableData = ref([]);
  const warmTableData = ref([]);
  const filterTableData = (data, year) => {
    const tableData = [];
    for (let i = 0; i < monthLists.length; i++) {
      const result = {};
      Reflect.set(result, 'month', monthLists[i]);
      forEach(data, el => {
        if (el.usageTime.substring(5, 7) === monthLists[i]) {
          forEach(year, e => {
            if (el.usageTime.substring(0, 4) === e) {
              Reflect.set(result, `${e}energyQuantity`, el.energyQuantity);
              Reflect.set(result, `${e}cost`, el.cost);
            }
          });
        }
      });
      tableData.push(result);
    }
    return tableData;
  };
  const [energyLists, typeLoading, typeRun] = useRequest(getEnergyHistory, {
    defaultParams: [],
    // manual: true,
  });
  const filterValue = (row, year, val) => {
    for (let i in row) {
      if (i == year + val) {
        return row[i];
      }
    }
  };
  useWatch(
    energyLists,
    n => {
      const obj = {
        ele: [],
        water: [],
        gas: [],
        warm: [],
      };
      n.rows.forEach(item => {
        if (item.energyType === '电' || item.energyType === 'ELECTRICITY') {
          obj.ele.push(item);
          if (eleYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
            eleYearlists.value.push(item.usageTime.substring(0, 4));
          }
        } else if (item.energyType === '水' || item.energyType === 'WATER') {
          obj.water.push(item);
          if (waterYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
            waterYearlists.value.push(item.usageTime.substring(0, 4));
          }
        } else if (item.energyType === '气' || item.energyType === 'AIR') {
          obj.gas.push(item);
          if (gasYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
            gasYearlists.value.push(item.usageTime.substring(0, 4));
          }
        } else if (item.energyType === '暖' || item.energyType === 'WARM') {
          obj.warm.push(item);
          if (warmYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
            warmYearlists.value.push(item.usageTime.substring(0, 4));
          }
        }
      });
      eleTableData.value = filterTableData(obj.ele, eleYearlists.value);
      waterTableData.value = filterTableData(obj.water, waterYearlists.value);
      gasTableData.value = filterTableData(obj.gas, gasYearlists.value);
      warmTableData.value = filterTableData(obj.warm, warmYearlists.value);
    },
    { deep: true },
  );

  return [
    waterYearlists,
    eleYearlists,
    gasYearlists,
    warmYearlists,
    waterTableData,
    eleTableData,
    gasTableData,
    warmTableData,
    energyLists,
    typeLoading,
    typeRun,
    filterValue,
  ];
};

export const useReportTable = () => {
  const reportTable = ref(null);
  const open = ref(false);
  const opentitle = ref('');
  const tableForm = ref({
    enterpriseCode: '',
    pageNum: 1,
    pageSize: 10,
  });
  const [enterpriseList, enterpriseListLoading] = useRequest(getList, {
    defaultParams: [{ enterpriseName: '' }],
  });
  const [reportTree, , reportRun] = useRequest(getReportTree, {
    defaultParams: [],
    manual: true,
  });
  const [kxxbgTableData, kxxbgLoading, kxxbgTableRun] = useRequest(getKxxbgLists, {
    defaultParams: [],
    manual: true,
    onSuccess: data => {
      reportTree.value = [];
    },
  });
  const [, , removeReportRun] = useRequest(removeReport, {
    defaultParams: [],
    manual: true,
    onSuccess: data => {
      Message.success('删除成功');
      let obj = useFormData(tableForm.value);
      kxxbgTableRun(obj);
    },
  });
  const select = (selection, row) => {
    if (selection.length > 1) {
      const del_row = selection.shift();
      reportTable.value.toggleRowSelection(del_row, false);
      reportRun({ reportCode: selection[0].reportCode });
    } else if (selection.length === 1) {
      reportRun({ reportCode: selection[0].reportCode });
    } else if (selection.length === 0) {
      reportTree.value = [];
    }
  };
  const handleRowClick = (row, column, event) => {
    forEach(kxxbgTableData.value.rows, n => {
      if (n.reportCode === row.reportCode && n.createTime === row.createTime) {
        reportTable.value.toggleRowSelection(n, true);
        reportRun({ reportCode: n.reportCode });
      } else {
        reportTable.value.toggleRowSelection(n, false);
      }
    });
  };
  const deleteKxxbgTable = (row, index) => {
    MessageBox.confirm('是否删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        let formdata = new FormData();
        formdata.append('reportCode', row.reportCode);
        removeReportRun(formdata);
      })
      .catch(() => {});
  };
  return [
    reportTable,
    open,
    opentitle,
    tableForm,
    enterpriseList,
    enterpriseListLoading,
    kxxbgTableData,
    kxxbgLoading,
    kxxbgTableRun,
    reportTree,
    select,
    handleRowClick,
    deleteKxxbgTable,
  ];
};
